<?php

namespace Frontend\Controllers;

use \COM;
use Forms\UploadForm;
use Models\Informations;
use Models\Documents;

class UploadController extends ControllerBase {

    public function indexAction() {
        
    }

    public function uploadAction() {
        $identify = $this->auth->getIdentity();
        if ($identify) {
            $form = new UploadForm();
            $support_files = array('doc', 'docx', 'pdf', 'ppt', 'pptx', 'txt');
            $uploap_guides = "";
            $uploap_rules = "";
            $guide = Informations::findFirstById('upload_guide');
            if ($guide) {
                $uploap_guides = $guide->value;
            }
            $rules = Informations::findFirstById('upload_rules');
            if ($rules) {
                $uploap_rules = $rules->value;
            }
            $this->view->upload_rules = $uploap_rules;
            $this->view->upload_guides = $uploap_guides;

            if ($this->request->isPost()) {
                if ($this->request->getPost('doctype')) {
                    $form = new UploadForm((object) ['doctype' => $this->request->getPost('doctype')]);
                }
                $request = $this->request->getPost();
                if ($_FILES["file"]) {
                    $request['file'] = $_FILES["file"]["name"];
                }
                if ($_FILES["image"]) {
                    $request['image'] = $_FILES["image"]["name"];
                }

                if ($form->isValid($request)) {
                    if (!$_FILES["file"]["error"]) {
                        $pathinfo = pathinfo($_FILES["file"]["name"]);
                        $extension = $pathinfo['extension'];
                        if (in_array($extension, $support_files)) {
                            $doc = new Documents();
                            $doc->assign(array(
                                'doctype_id' => $request['doctype'],
                                'topic_id' => $request['topic'],
                                'title' => $request['title'],
                                'link' => $request['file'],
                                'cost' => $request['cost'],
                                'description' => $request['description'],
                                'uploadby' => $identify['id'],
                                'submit_date' => date('Y-m-d H:i:s'),
                                'image' => '',
                                'discount' => 0,
                                'download' => 0,
                                'public' => 0,
                            ));
                            if ($doc->save()) {
                                $upload_dir = UPLOAD_DIR . $request['doctype'] . '/' . $request['topic'] . '/' . $doc->id . '/';
                                $review_dir = REVIEW_DIR . '/' . $request['topic'] . '/' . $doc->id . '/';
                                if (!file_exists($upload_dir)) {
                                    mkdir($upload_dir, 0777, true);
                                }
                                if (!file_exists($review_dir)) {
                                    mkdir($review_dir, 0777, true);
                                }
                                if (in_array($extension, array('doc', 'docx', 'txt'))) {
                                    try {
                                        $word = new COM("Word.Application") or die("Could not initialise Object.");
                                        // set it to 1 to see the MS Word window (the actual opening of the document)
                                        $word->Visible = 0;
                                        // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc"
                                        $word->DisplayAlerts = 0;
                                        // open the word 2007-2013 document 
                                        $word->Documents->Open($_FILES["file"]["tmp_name"]);
                                        // convert word 2007-2013 to PDF
                                        $word->ActiveDocument->ExportAsFixedFormat($review_dir . $_FILES["file"]["name"] . '.pdf', 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);
                                        // quit the Word process
                                        $word->Quit(false);
                                        // clean up
                                        unset($word);
                                        require_once('../app/library/pdf/fpdf.php');
                                        require_once('../app/library/pdf/fpdi.php');

                                        $pdf = new \FPDI();

                                        $pdf->AddPage();
                                        $pdf->setSourceFile($review_dir . $_FILES["file"]["name"] . '.pdf');

                                        $tplidx = $pdf->importPage(1);
                                        for ($i = 1; $i <= 6; $i++) {
                                            $tplidx = $pdf->ImportPage($i);
                                            $pdf->useTemplate($tplidx, 10, 10, 200);
                                            $pdf->AddPage();
                                        }
                                        $pdf->Output($review_dir . $_FILES["file"]['name'] . '.pdf');
                                        $doc->review = $_FILES["file"]["name"] . '.pdf';
                                    } catch (\Exception $e) {
                                        $doc->review = '';
                                        $form->appendMessage("Không thể tạo file xem trước", "upload_info", null);
                                    }
                                }
                                if ($extension == 'pdf') {
                                    try {
                                        require_once('../app/library/pdf/fpdf.php');
                                        require_once('../app/library/pdf/fpdi.php');

                                        $pdf = new \FPDI();

                                        $pdf->AddPage();
                                        $pdf->setSourceFile($_FILES["file"]['tmp_name']);

                                        $tplidx = $pdf->importPage(1);
                                        for ($i = 1; $i <= 6; $i++) {
                                            $tplidx = $pdf->ImportPage($i);
                                            $pdf->useTemplate($tplidx, 10, 10, 200);
                                            $pdf->AddPage();
                                        }
                                        $pdf->Output($review_dir . $_FILES["file"]['name']);
                                        $doc->review = $_FILES["file"]["name"];
                                    } catch (\Exception $e) {
                                        $doc->review = '';
                                        $form->appendMessage("Không thể tạo file xem trước", "upload_info", null);
                                    }
                                }
                                move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir . $_FILES["file"]["name"]);

                                // Upload image
                                if (!$_FILES['image']['error']) {
                                    move_uploaded_file($_FILES["image"]["tmp_name"], $review_dir . $_FILES["image"]["name"]);
                                    $doc->image = $_FILES["image"]["name"];
                                }
                                $doc->save();
                                $form->appendMessage("Upload file thành công", "upload_info", null);
                            } else {
                                foreach ($doc->getMessages() as $value) {
                                    $form->appendMessage($value, "upload_info", null);
                                }
                            }
                        } else {

                            $form->appendMessage("Định dạng file không hỗ trợ", "upload_info", null);
                        }
                    } else {                        
                        $form->appendMessage("Fail to Upload File", "upload_info", null);
                    }
                }
            }
            $this->view->form = $form;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'frontend',
                'controller' => 'user',
                'action' => 'login',
            ));
        }
    }

}
